package cn.wolfcode.shop.seckill.service.impl;


import cn.wolfcode.cloud.exception.BusinessException;
import cn.wolfcode.cloud.redis.RedisService;
import cn.wolfcode.shop.seckill.domain.OrderInfo;
import cn.wolfcode.shop.seckill.domain.SeckillOrder;
import cn.wolfcode.shop.seckill.mapper.SeckillOrderMapper;
import cn.wolfcode.shop.seckill.redis.SeckillKeyPrefix;
import cn.wolfcode.shop.seckill.result.SeckillGoodServerCodeMsg;
import cn.wolfcode.shop.seckill.service.IOrderService;
import cn.wolfcode.shop.seckill.service.ISeckillGoodService;
import cn.wolfcode.shop.seckill.service.ISeckillOrderService;
import cn.wolfcode.shop.seckill.vo.SeckillGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SeckillOrderServiceImpl implements ISeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisService redisService;

    @Override
    public SeckillOrder findByUserIdAndGoodId(Long userId, Long goodId) {
        return seckillOrderMapper.findByUserIdAndGoodId(userId,goodId);
    }

    @Override
    @Transactional
    public String doSeckill(SeckillGoodVo seckillGoodVo, Long id) {
        //扣减商品库存
        int order = seckillGoodService.reduce(seckillGoodVo.getId());
        if(order > 0) {
            //创建商品订单
            OrderInfo orderInfo = orderService.createOrderInfo(seckillGoodVo, id);
            //创建秒杀订单
            createSeckillOrder(orderInfo);
            redisService.set(SeckillKeyPrefix.SECKILLGOODORDER,orderInfo.getUserId()+":"+orderInfo.getGoodId(),orderInfo);
            return orderInfo.getOrderNo();
        }else{
            throw new BusinessException(SeckillGoodServerCodeMsg.SG_ERROR);
        }
    }

    @Override
    public int createSeckillOrder(OrderInfo orderInfo) {
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodId(orderInfo.getGoodId());
        seckillOrder.setOrderNo(orderInfo.getOrderNo());
        seckillOrder.setUserId(orderInfo.getUserId());
        int count = seckillOrderMapper.createSeckillOrder(seckillOrder);
        return count;
    }

    @Override
    public int updateStatus(String orderNo) {
        return seckillOrderMapper.updateStatus(orderNo);
    }


}
